package org.ezplatform.office.questionnaire.web.rest;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.ezplatform.cloud.api.component.attachment.AttachmentUtilsService;
import org.ezplatform.cloud.api.system.user.UserApiService;
import org.ezplatform.cloud.common.util.AuthUtils;
import org.ezplatform.core.common.WebUser;
import org.ezplatform.core.exception.ValidationException;
import org.ezplatform.core.pagination.PropertyFilter;
import org.ezplatform.core.service.BaseService;
import org.ezplatform.core.web.controller.BaseController;
import org.ezplatform.core.web.util.WebUtils;
import org.ezplatform.core.web.view.OperationResult;
import org.ezplatform.office.questionnaire.entity.Questionnaire;
import org.ezplatform.office.questionnaire.entity.QuestionnaireAnswer;
import org.ezplatform.office.questionnaire.entity.QuestionnaireTopic;
import org.ezplatform.office.questionnaire.entity.QuestionnaireTopicOptions;
import org.ezplatform.office.questionnaire.entity.QusetionnaireAnswerStatus;
import org.ezplatform.office.questionnaire.service.QuesCache;
import org.ezplatform.office.questionnaire.service.QuestionnaireAnswerService;
import org.ezplatform.office.questionnaire.service.QuestionnaireAnswerStatusService;
import org.ezplatform.office.questionnaire.service.QuestionnaireService;
import org.ezplatform.office.questionnaire.service.QuestionnaireTopicService;
import org.ezplatform.office.questionnaire.util.SendMsgUtils;
import org.ezplatform.util.GlobalConstant;
import org.ezplatform.util.JsonUtils;
import org.ezplatform.util.RestClient;
import org.ezplatform.util.StringUtils;
import org.ezplatform.util.ValidateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;

import ch.qos.logback.core.net.SyslogOutputStream;

@RestController
@RequestMapping(value = "/api/w/questionnaire/questionnaire/answer")
public class QuestionnairAnswerWebApiController extends BaseController<QuestionnaireAnswer,String>{
	
	private final static org.slf4j.Logger LOGGER = org.slf4j.LoggerFactory.getLogger(QuestionnairAnswerWebApiController.class);
	
	@Autowired
	private QuestionnaireAnswerService answerService;
	
	@Autowired
	private QuestionnaireTopicService topicService;

	@Autowired
	private QuestionnaireAnswerStatusService anStatusService;
	
	@Autowired
	private AttachmentUtilsService attachmentUtilsService;

	@Autowired
	private QuestionnaireService questionnaireService;

	@Autowired
	public UserApiService userApiService;
	
	@Autowired
	public QuesCache quesCache;

	@Override
	protected BaseService<QuestionnaireAnswer, String> getEntityService() {
		return answerService;
	}
	
	/**
     * 初始化数据
     * 
     * @param request
     * @param model
     * @param id
     */
    @ModelAttribute
    public void prepareModel(HttpServletRequest request, Model model,
            @RequestParam(value = "id", required = false) String id) {
        super.initPrepareModel(request, model, id);
    }
    
    /**
     * 获取列表（翻页）数据
     * 
     * @param request
     * @return json
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public Page<Map> findByPage(HttpServletRequest request) {
		WebUser user = WebUtils.getCurrentUser();
    	Pageable pageable = PropertyFilter.buildPageableFromHttpRequest(request);
		List<PropertyFilter> propertyFilter = PropertyFilter.buildFiltersFromHttpRequest(QuestionnaireAnswer.class,request);
		Boolean isSuperAdmin = AuthUtils.isSuperAdmin(user);
		String status = request.getParameter("status");
		if(StringUtils.isNotBlank(status) && !ValidateUtils.validateInt(status)) {
			throw new ValidationException("非法参数");
		}
		Page<Map> page = answerService.getAnswerMap(pageable,propertyFilter,status,user.getUserId(),isSuperAdmin,user.getJwtToken());
		return page;
    }
    
    /**
     * 问卷统计分析答卷列表
     * 
     * @param request
     * @return json
     */
    @RequestMapping(value = "/statisticsAnswer", method = RequestMethod.GET)
    @ResponseBody
    public Page<Map> statisticsAnswer(HttpServletRequest request) {
    	WebUser user = WebUtils.getCurrentUser();
    	String quesitionnaireId = request.getParameter("quesitionnaireId");
    	if(quesitionnaireId != null && !ValidateUtils.validateId(quesitionnaireId)) {
            throw new ValidationException("非法参数");
        }
    	Pageable pageable = PropertyFilter.buildPageableFromHttpRequest(request);
		List<PropertyFilter> propertyFilter = PropertyFilter.buildFiltersFromHttpRequest(QuestionnaireAnswer.class,request);
		String searchName = request.getParameter("userName");
		if(searchName != null && !ValidateUtils.validateChar(searchName, "%+") ){
	    	throw new ValidationException("非法参数");
	    }
		String departmentName = request.getParameter("departmentName");
		if(departmentName != null && !ValidateUtils.validateChar(departmentName, "%+") ){
	    	throw new ValidationException("非法参数");
	    }
		String status = request.getParameter("status");
		if(StringUtils.isNotBlank(status) && !ValidateUtils.validateInt(status)) {
			throw new ValidationException("非法参数");
		}
		Page<Map> page = answerService.getStatisticsAnswerInfo(pageable, propertyFilter, quesitionnaireId, 
				searchName, departmentName,status,user.getJwtToken(),user.getUserId());
		return page;
    }
    
    /**
     * 问卷统计分析未答卷列表
     * 
     * @param request
     * @return json
     */
    @RequestMapping(value = "/statisticsNoAnswer", method = RequestMethod.GET)
    @ResponseBody
    public Page<Map> statisticsNoAnswer(HttpServletRequest request) {
    	WebUser user = WebUtils.getCurrentUser();
    	String quesitionnaireId = request.getParameter("quesitionnaireId");
    	if(quesitionnaireId != null && !ValidateUtils.validateId(quesitionnaireId)){
    		throw new ValidationException("非法参数");
	    }
    	Pageable pageable = PropertyFilter.buildPageableFromHttpRequest(request);
		List<PropertyFilter> propertyFilter = PropertyFilter.buildFiltersFromHttpRequest(QuestionnaireAnswer.class,request);
		String searchName = request.getParameter("userName");
	    if(searchName != null && !ValidateUtils.validateChar(searchName, "%+") ){
	    	throw new ValidationException("非法参数");
	    }
		String departmentName = request.getParameter("departmentName");
	    if(departmentName != null && !ValidateUtils.validateChar(departmentName, "%+") ){
	    	throw new ValidationException("非法参数");
	    }
		Page<Map> page =
				answerService.getStatisticsNoAnswerInfo(
						pageable, propertyFilter, quesitionnaireId, searchName, departmentName,user.getJwtToken(), user.getCorpId());
		return page;
    }
    
    /**
     * 查询问卷题目
     * @return
     */
	@RequestMapping(value = "/getQues")
    @ResponseBody
    public OperationResult getQues(HttpServletRequest request) {
		long time1=System.currentTimeMillis();
		WebUser user = WebUtils.getCurrentUser();  
		String quesitionnaireId = request.getParameter("quesitionnaireId");
		if(quesitionnaireId != null && !ValidateUtils.validateId(quesitionnaireId)){
    		throw new ValidationException("非法参数");
	    }
		long time=System.currentTimeMillis();
		String userId = user.getUserId();
		String corpId = user.getCorpId();
		List<QuestionnaireTopic> list = topicService.getTopicOPtionInfo(quesitionnaireId,userId,user.getJwtToken(),true);
//		LOGGER.error(userId+":user:1:"+(System.currentTimeMillis()-time));
//		time=System.currentTimeMillis();
		Map<String, Object> map = new HashMap<>();
		QusetionnaireAnswerStatus qusetionnaireAnswerStatus =
				anStatusService.findAnswerStatus(user.getUserId(),quesitionnaireId);
//		LOGGER.error(userId+":user:2:"+(System.currentTimeMillis()-time));
//		time=System.currentTimeMillis();
		if(qusetionnaireAnswerStatus != null){
			map.put("anStatus",qusetionnaireAnswerStatus.getStatus());
			map.put("anGrade",qusetionnaireAnswerStatus.getGrade());
			map.put("ranking",qusetionnaireAnswerStatus.getRanking());
			map.put("answerNum",qusetionnaireAnswerStatus.getAnswerNum());
		}
		//Lambda表达式 查询所有分页页数
		List<String> pageList = list.stream().map((topic)->{
			if(StringUtils.equals(topic.getTopicType(),"paging")){
				return topic.getPage();
			}else{
				return null;
			}
		}).collect(Collectors.toList());
//		LOGGER.error(userId+":user:3:"+(System.currentTimeMillis()-time));
//		time=System.currentTimeMillis();
		if (CollectionUtils.isNotEmpty(list)) {
			int index = 0;
			for (int i = 0; i < list.size(); i++) {
				QuestionnaireTopic questionnaireTopic = list.get(i);
				String topicType = questionnaireTopic.getTopicType();
				if (!"paging".equals(topicType) && !"illustrate".equals(topicType)) {
					index++;
				}
				questionnaireTopic.setTopicNo(String.valueOf(index));
			}
		}
//		LOGGER.error(userId+":user:4:"+(System.currentTimeMillis()-time));
//		time=System.currentTimeMillis();
		map.put("topicSetting", list);
		if(CollectionUtils.isNotEmpty(pageList)){
			pageList.removeAll(Collections.singleton(null));
			if(pageList.size() == 0){
				map.put("page",0);
			}else{
				map.put("page",pageList.size());
			}
		}else{
			map.put("page",0);
		}
		LOGGER.error(userId+":user:5:"+(System.currentTimeMillis()-time));
		time=System.currentTimeMillis();
		String url ="";
		if(list != null && list.size() > 0) {
			for (QuestionnaireTopic questionnaireTopic : list) {
				if(questionnaireTopic.getList() != null && questionnaireTopic.getList().size() > 0) {
					for(int j=0;j<questionnaireTopic.getList().size();j++){
						QuestionnaireTopicOptions option = questionnaireTopic.getList().get(j);
						String jsonVal = option.getOptionSetting();
						QuestionnaireAnswer answer = option.getAnswer();
						if(StringUtils.isNotBlank(jsonVal) && !jsonVal.contains("option-option") && jsonVal.contains("optionImg")) {
							JSONObject jsStr = JSONObject.parseObject(jsonVal);
							if( jsStr.getString("optionImg") != null && !"".equals(jsStr.getString("optionImg"))) {
								List<Map<String, String>> fileInfoList =attachmentUtilsService.getAttachmentByIds(jsStr.getString("optionImg"), corpId, user.getJwtToken());
								url = "/attachment/image?fid="+jsStr.getString("optionImg")+"&chksum="+fileInfoList.get(0).get("checksum");
								answer.setAttachment(url);
								option.setAnswer(answer);
							}
						}
					}
				}
				
			}
		}
		LOGGER.error(userId+":user:6:"+(System.currentTimeMillis()-time));
		time=System.currentTimeMillis();
		map.put("topicSetting", list);
    	Questionnaire oq = questionnaireService.findOne(quesitionnaireId);
    	String titleSetting = StringUtils.null2String(oq.getTitleSetting());
    	if(!"".equals(titleSetting)){
    		Map<String, Object> mapSetting = new HashMap<String, Object>();
    		mapSetting = JsonUtils.readValue(titleSetting);
    		map.put("titleSetting", mapSetting);
    	}else{
    		map.put("titleSetting", titleSetting);
    	}
//    	LOGGER.error(userId+":user:7:"+(System.currentTimeMillis()-time));
//		time=System.currentTimeMillis();
    	map.put("entity", oq);
    	map.put("flexServerPath", GlobalConstant.getFlexServerPath(request));
    	map.put("answerCount",  anStatusService.getAnswerNumByQuesId(quesitionnaireId));//答卷人数
//    	LOGGER.error(userId+":user:8:"+(System.currentTimeMillis()-time));
    	LOGGER.error(userId+":user:last:"+(System.currentTimeMillis()-time1));
//		time=System.currentTimeMillis();
		return OperationResult.buildSuccessResult(map);
	}
	
	/**
     * 保存答卷
     * @return
     */
    @RequestMapping(value = "/answerEdit", method = RequestMethod.POST)
    @ResponseBody
    public OperationResult answerEdit(HttpServletRequest request) {
    	Map i18nKey=new HashMap(1);
    	String orgId = "";
    	WebUser user = WebUtils.getCurrentUser();
    	Object object = quesCache.get(user.getUserId());
    	if(object != null) {
    		orgId = String.valueOf(object);
    	}else {
    		List<Map<String,Object>> userMapList = userApiService.getUserRelatedInfo(user.getUserId(),"1",user.getCorpId(),user.getJwtToken());
    		if(CollectionUtils.isNotEmpty(userMapList)){
    			/*for(Map<String,Object> map : userMapList){
    			    orgId = StringUtils.null2String(map.get("orgId"));
    			}*/
    			
    			orgId = StringUtils.null2String(userMapList.get(0).get("orgId"));
    			quesCache.set(user.getUserId(), orgId);
    		}
    	}
		
    	List<QuestionnaireAnswer> list = new ArrayList<QuestionnaireAnswer>();
    	String userId = WebUtils.getCurrentUser().getUserId();
    	String quesitionnaireId = request.getParameter("quesitionnaireId");
    	if(quesitionnaireId != null && !ValidateUtils.validateId(quesitionnaireId)){
    		throw new ValidationException("非法参数");
	    }
    	// 自动保存标记：1-是，其他-否
    	String timingFlag = request.getParameter("timingFlag");
    	if(timingFlag != null && !ValidateUtils.validateParam(timingFlag)){
    		throw new ValidationException("非法参数");
	    }
    	String anStatus = request.getParameter("answerStatus");
    	
    	Questionnaire ques = new Questionnaire();
    	if(quesitionnaireId!=null) {
    		ques = questionnaireService.findOne(quesitionnaireId);
    	}
    	QusetionnaireAnswerStatus aStatus = anStatusService.findAnswerStatus(userId,quesitionnaireId);
    	if(aStatus != null && (QusetionnaireAnswerStatus.StatusEnum.SUBMIT.getCode().equals(aStatus.getStatus())||QusetionnaireAnswerStatus.StatusEnum.APPROVED.getCode().equals(aStatus.getStatus()))) {
    		if(!canToAnswer(aStatus,ques)) {
    			i18nKey.put("i18NCode", "oa.que.submitted");
        		return OperationResult.buildFailureResult("已提交");
    		}
    	}
    	String[] sinselect = request.getParameterValues("sinselect");
    	if(sinselect != null && !ValidateUtils.validateId(sinselect)){
    		throw new ValidationException("非法参数");
	    }
    	String[] trueOrFalse = request.getParameterValues("trueOrFalse");
    	if(trueOrFalse != null && !ValidateUtils.validateId(trueOrFalse)){
    		throw new ValidationException("非法参数");
	    }
    	String[] multiselect = request.getParameterValues("multiselect");
    	if(multiselect != null && !ValidateUtils.validateId(multiselect)){
    		throw new ValidationException("非法参数");
	    }
    	String[] check = request.getParameterValues("check");
    	if(check != null && !ValidateUtils.validateId(check)){
    		throw new ValidationException("非法参数");
	    }
    	String[] fillInBlanks = request.getParameterValues("fillInBlanks");
    	if(fillInBlanks != null && !ValidateUtils.validateId(fillInBlanks)){
    		throw new ValidationException("非法参数");
	    }
    	String[] answer = request.getParameterValues("answer");
    	if(answer != null && !ValidateUtils.validateId(answer)){
    		throw new ValidationException("非法参数");
	    }
    	String[] shortAnswer = request.getParameterValues("shortAnswer");
    	if(shortAnswer != null && !ValidateUtils.validateId(shortAnswer)){
    		throw new ValidationException("非法参数");
	    }
    	String[] field = request.getParameterValues("field");
    	if(field != null && !ValidateUtils.validateId(field)){
    		throw new ValidationException("非法参数");
	    }
    	String[] scale = request.getParameterValues("scale");
    	if(scale != null && !ValidateUtils.validateId(scale)){
    		throw new ValidationException("非法参数");
	    }
    	String[] mulscale = request.getParameterValues("mulscale");
    	if(mulscale != null && !ValidateUtils.validateId(mulscale)){
    		throw new ValidationException("非法参数");
	    }
    	if(sinselect != null && sinselect.length>0){
    		for(int i=0;i<sinselect.length;i++){
    			String topicId = sinselect[i];
    			String topicAllSetting = request.getParameter("sinselect"+topicId);
    			Map<String,Object> map = JsonUtils.readValue(topicAllSetting);
    			QuestionnaireAnswer oaAnswer = new QuestionnaireAnswer();
    			oaAnswer.setAnswer((String)map.get("answer"));
    			oaAnswer.setTopicId(topicId);
    			oaAnswer.setQuestionnaireId(quesitionnaireId);
    			oaAnswer.setOptionId((String)map.get("optionId"));
    			oaAnswer.setUserId(userId);
    			oaAnswer.setAnswerExt((String)map.get("answerExt"));
    			String franction = (String)map.get("franction");
    			if(!"".equals(StringUtils.null2String(franction))){
    				oaAnswer.setFraction(Float.parseFloat((String)map.get("franction")));
    			}
    			list.add(oaAnswer);
    		} 
    	} 
    	if(trueOrFalse != null && trueOrFalse.length>0){
    		for(int i=0;i<trueOrFalse.length;i++){
    			String topicId = trueOrFalse[i];
    			String topicAllSetting = request.getParameter("trueOrFalse"+topicId);
    			Map<String,Object> map = JsonUtils.readValue(topicAllSetting);
    			QuestionnaireAnswer oaAnswer = new QuestionnaireAnswer();
    			oaAnswer.setAnswer((String)map.get("answer"));
    			oaAnswer.setTopicId(topicId);
    			oaAnswer.setQuestionnaireId(quesitionnaireId);
    			oaAnswer.setOptionId((String)map.get("optionId"));
    			oaAnswer.setUserId(userId);
    			String franction = (String)map.get("franction");
    			if(!"".equals(StringUtils.null2String(franction))){
    				oaAnswer.setFraction(Float.parseFloat((String)map.get("franction")));
    			}
    			list.add(oaAnswer);
    		} 
    	}
    	if(multiselect !=null && multiselect.length>0){
    		for(int i=0;i<multiselect.length;i++){
    			String topicId = multiselect[i];
    			String topicAllSettings= request.getParameter("multiselect"+topicId);
    			String[] str = topicAllSettings.split("answer-answer");
    			for(int j=0;j<str.length;j++){
    				String topicAllSetting = str[j];
    				if(topicAllSetting!=null && !"".equals(topicAllSetting)){
    					Map<String,Object> map = JsonUtils.readValue(topicAllSetting);
    	    			QuestionnaireAnswer oaAnswer = new QuestionnaireAnswer();
    	    			oaAnswer.setAnswer((String)map.get("answer"));
    	    			oaAnswer.setTopicId(topicId);
    	    			oaAnswer.setQuestionnaireId(quesitionnaireId);
    	    			oaAnswer.setOptionId((String)map.get("optionId"));
    	    			oaAnswer.setUserId(userId);
    	    			oaAnswer.setAnswerExt((String)map.get("answerExt"));
    	    			String franction = (String)map.get("franction");
    	    			if(!"".equals(StringUtils.null2String(franction))){
    	    				oaAnswer.setFraction(Float.parseFloat((String)map.get("franction")));
    	    			}
    	    			list.add(oaAnswer);
    				}
    			}
    		}
    	} 
    	if(check != null && check.length>0){
    		for(int i=0;i<check.length;i++){
    			String topicId = check[i];
    			String topicAllSetting = request.getParameter("check"+topicId);
    			Map<String,Object> map = JsonUtils.readValue(topicAllSetting);
    			QuestionnaireAnswer oaAnswer = new QuestionnaireAnswer();
    			oaAnswer.setAnswer((String)map.get("answer"));
    			oaAnswer.setTopicId(topicId);
    			oaAnswer.setQuestionnaireId(quesitionnaireId);
    			oaAnswer.setOptionId((String)map.get("optionId"));
    			oaAnswer.setUserId(userId);
    			String franction = (String)map.get("franction");
    			if(!"".equals(StringUtils.null2String(franction))){
    				oaAnswer.setFraction(Float.parseFloat((String)map.get("franction")));
    			}
    			list.add(oaAnswer);
    		} 
    	} 
    	if(fillInBlanks !=null && fillInBlanks.length>0){
    		for(int i=0;i<fillInBlanks.length;i++){
    			String topicId = fillInBlanks[i];
    			String topicAllSettings= request.getParameter("fillInBlanks"+topicId);
    			String[] str = topicAllSettings.split("answer-answer");
    			for(int j=0;j<str.length;j++){
    				String topicAllSetting = str[j];
    				if(topicAllSetting!=null && !"".equals(topicAllSetting)){
    					Map<String,Object> map = JSONObject.parseObject(topicAllSetting);
    	    			QuestionnaireAnswer oaAnswer = new QuestionnaireAnswer();
    	    			oaAnswer.setAnswer((String)map.get("answer"));
    	    			oaAnswer.setTopicId(topicId);
    	    			oaAnswer.setQuestionnaireId(quesitionnaireId);
    	    			oaAnswer.setOptionId((String)map.get("optionId"));
    	    			oaAnswer.setUserId(userId);
    	    			String franction = (String)map.get("franction");
    	    			if(!"".equals(StringUtils.null2String(franction))){
    	    				oaAnswer.setFraction(Float.parseFloat((String)map.get("franction")));
    	    			}
    	    			list.add(oaAnswer);
    				}
    				
    			}
    		}
    	} 
    	if(answer !=null && answer.length>0){
    		for(int i=0;i<answer.length;i++){
    			String topicId = answer[i];
    			String topicAllSetting = request.getParameter("answer"+topicId);
    			Map<String,Object> map = JSONObject.parseObject(topicAllSetting);
    			QuestionnaireAnswer oaAnswer = new QuestionnaireAnswer();
    			oaAnswer.setAnswer((String)map.get("answer"));
    			oaAnswer.setTopicId(topicId);
    			oaAnswer.setQuestionnaireId(quesitionnaireId);
    			oaAnswer.setOptionId((String)map.get("optionId"));
    			oaAnswer.setUserId(userId);
    			String franction = (String)map.get("franction");
    			if(!"".equals(StringUtils.null2String(franction))){
    				oaAnswer.setFraction(Float.parseFloat((String)map.get("franction")));
    			}
    			list.add(oaAnswer);
    		} 
    	} 
    	if(shortAnswer !=null && shortAnswer.length>0){
    		for(int i=0;i<shortAnswer.length;i++){
    			String topicId = shortAnswer[i];
    			String topicAllSetting = request.getParameter("shortAnswer"+topicId);
    			topicAllSetting=topicAllSetting.replace("\r", "\\r").replace("\n", "\\n");
    			Map<String,Object> map = JsonUtils.readValue(topicAllSetting);
    			QuestionnaireAnswer oaAnswer = new QuestionnaireAnswer();
    			oaAnswer.setAnswer((String)map.get("answer"));
    			oaAnswer.setTopicId(topicId);
    			oaAnswer.setQuestionnaireId(quesitionnaireId);
    			oaAnswer.setOptionId((String)map.get("optionId"));
    			oaAnswer.setUserId(userId);
    			String franction = (String)map.get("franction");
    			if(!"".equals(StringUtils.null2String(franction))){
    				oaAnswer.setFraction(Float.parseFloat((String)map.get("franction")));
    			}
    			list.add(oaAnswer);
    		} 
    	} 
    	if(field !=null && field.length>0){
    		for(int i=0;i<field.length;i++){
    			String topicId = field[i];
    			String topicAllSetting = request.getParameter("field"+topicId);
    			Map<String,Object> map = JsonUtils.readValue(topicAllSetting);
    			QuestionnaireAnswer oaAnswer = new QuestionnaireAnswer();
    			oaAnswer.setAnswer((String)map.get("answer"));
    			oaAnswer.setTopicId(topicId);
    			oaAnswer.setQuestionnaireId(quesitionnaireId);
    			oaAnswer.setOptionId((String)map.get("optionId"));
    			oaAnswer.setUserId(userId);
    			list.add(oaAnswer);
    		} 
    	} 
    	if(scale !=null && scale.length>0){
    		for(int i=0;i<scale.length;i++){
    			String topicId = scale[i];
    			String topicAllSetting = request.getParameter("scale"+topicId);
    			Map<String,Object> map = JsonUtils.readValue(topicAllSetting);
    			QuestionnaireAnswer oaAnswer = new QuestionnaireAnswer();
    			oaAnswer.setAnswer((String)map.get("answer"));
    			oaAnswer.setTopicId(topicId);
    			oaAnswer.setQuestionnaireId(quesitionnaireId);
    			oaAnswer.setOptionId((String)map.get("optionId"));
    			oaAnswer.setUserId(userId);
    			String franction = (String)map.get("franction");
    			if(!"".equals(StringUtils.null2String(franction))&&franction!=null){
    				oaAnswer.setFraction(Float.parseFloat((String)map.get("franction")));
    			}
    			list.add(oaAnswer);
    		} 
    	} 
    	if(mulscale != null && mulscale.length>0){
    		for(int i=0;i<mulscale.length;i++){
    			String topicId = mulscale[i];
    			String topicAllSetting = request.getParameter("mulscale"+topicId);
    			String[] topicAllSettings =topicAllSetting.split("##");
    			for(int j=0;j<topicAllSettings.length;j++){
    				Map<String,Object> map = JsonUtils.readValue(topicAllSettings[j]);
        			QuestionnaireAnswer oaAnswer = new QuestionnaireAnswer();
        			oaAnswer.setAnswer((String)map.get("answer"));
        			oaAnswer.setTopicId(topicId);
        			oaAnswer.setQuestionnaireId(quesitionnaireId);
        			oaAnswer.setOptionId((String)map.get("optionId"));
        			oaAnswer.setUserId(userId);
        			String franction = (String)map.get("franction");
        			if(!"".equals(StringUtils.null2String(franction))&&franction!=null){
        				oaAnswer.setFraction(Float.parseFloat((String)map.get("franction")));
        			}
        			list.add(oaAnswer);
    			}
    		}
    	} 
    	answerService.deleteAnswerByQuesId(userId, quesitionnaireId);
    	answerService.save(list);
    	// 自动保存不更新答卷状态
    	if (!"1".equals(timingFlag)) {
    		String grade = request.getParameter("grade");
        	//答卷状态 1是提交，2是草稿，4评卷
        	QusetionnaireAnswerStatus answerStatus = aStatus;
    		Date date = new Date();
    		if(answerStatus ==null){
        		QusetionnaireAnswerStatus newAnswerStatus = new QusetionnaireAnswerStatus();
        		newAnswerStatus.setOrgId(orgId);
        		newAnswerStatus.setQuestionnaireId(quesitionnaireId);
        		newAnswerStatus.setStatus(anStatus);
        		newAnswerStatus.setAnswerNum(1);
        		if(StringUtils.isNotEmpty(grade)) newAnswerStatus.setGrade(Float.parseFloat(grade));
        		anStatusService.save(newAnswerStatus);
        	}else{
    			answerStatus.setOrgId(orgId);
    			answerStatus.setStatus(anStatus);
    			answerStatus.setCreatedDate(date);
    			answerStatus.setAnswerNum(answerStatus.getAnswerNum()+1);
    			if(StringUtils.isNotEmpty(grade)) answerStatus.setGrade(Float.parseFloat(grade));
        		anStatusService.save(answerStatus);
        	}
    	}
    	String quesitionnaireType = request.getParameter("quesitionnaireType");
		//if("questionnaireExam".equals(quesitionnaireType) && "1".equals(anStatus)) {
			//并发量大的时候可不能这么搞,排名更新放在统计排名导出
			//anStatusService.rankingByGrade(quesitionnaireId);//无主观题直接进行排名
		//}
    	if("1".equals(anStatus) || "4".equals(anStatus)) {
    		new Thread(new Runnable() {
				@Override
				public void run() {
					RestClient restClient = new RestClient(true);
		    	    Map<String, String> paramMap = new HashMap<String, String>();
		    	    paramMap.put("receiver","[{\"10\":\"" + user.getUserId() + "\"}]");
		    	    paramMap.put("corpId", user.getCorpId());
		    	    paramMap.put("moduleCode", "questionnaire");
		    	    paramMap.put("dataId", quesitionnaireId);
		    	    paramMap.put("msgType", "1");
		    	    String jsonStr = restClient.post("/system/umc/message/takeMsgDone", user.getJwtToken(), paramMap);
				}},"sendQuestionnaireThread").start();
    	    /*RestClient restClient = new RestClient(true);
    	    Map<String, String> paramMap = new HashMap<String, String>();
    	    paramMap.put("receiver","[{\"10\":\"" + user.getUserId() + "\"}]");
    	    paramMap.put("corpId", user.getCorpId());
    	    paramMap.put("moduleCode", "questionnaire");
    	    paramMap.put("dataId", quesitionnaireId);
    	    paramMap.put("msgType", "1");
    	    String jsonStr = restClient.post("/system/umc/message/takeMsgDone", user.getJwtToken(), paramMap);*/
//    	    Map<String, Object> result = JsonUtils.readValue(jsonStr);
//    	    if(MapUtils.isNotEmpty(result)) {
//    	      if("failure".equals(result.get("type"))) {
//    	    	  LOGGER.error(String.valueOf(result.get("message")));
//    	    	  QusetionnaireAnswerStatus answerStatus = anStatusService.findAnswerStatus(userId,quesitionnaireId);
//    	    	  answerStatus.setStatus("0");
//    	    	  anStatusService.save(answerStatus);
//    	    	  i18nKey.put("i18NCode", "oa.que.remindedgetmessage");
//    	    	  return OperationResult.buildFailureResult("还未收到消息提醒，收到提醒后方可答卷",i18nKey);
//    	    	  
//    	      }
//    	    }
    	    i18nKey.put("i18NCode", "oa.que.submitok");
    		return OperationResult.buildSuccessResult("提交成功",i18nKey);
    	}else {
    		i18nKey.put("i18NCode", "oa.que.savesuccess");
    		return OperationResult.buildSuccessResult("保存成功",i18nKey);
    	}
    }
    
    /**
     * 查询问卷题目
     * @return
     */
	@RequestMapping(value = "/getStatistics")
    @ResponseBody
    public OperationResult getStatistics(HttpServletRequest request) {
		WebUser user = WebUtils.getCurrentUser();
		String corpId = user.getCorpId();
		String questionnaireId = request.getParameter("questionnaireId");
		if(questionnaireId != null && !ValidateUtils.validateId(questionnaireId)){
    		throw new ValidationException("非法参数");
	    }
		//答卷数
		int num = anStatusService.getAnswerNumByQuesId(questionnaireId, "1");
		//答卷总人数,优化：没必要查询，因为后面代码就没用上
		int allUser = 0;//topicService.getQuestAnswerNum(questionnaireId, user.getJwtToken(), corpId);
		Map<String, Object> map = new HashMap<>();
		Questionnaire oq = questionnaireService.findOne(questionnaireId);
		List<QuestionnaireTopic> list = topicService.getStatistics(questionnaireId,num,allUser,oq.getType());
		if (CollectionUtils.isNotEmpty(list)) {
			int index = 0;
			for (int i = 0; i < list.size(); i++) {
				QuestionnaireTopic questionnaireTopic = list.get(i);
				String topicType = questionnaireTopic.getTopicType();
				if (!"paging".equals(topicType) && !"illustrate".equals(topicType)) {
					index++;
				}
				questionnaireTopic.setTopicNo(String.valueOf(index));
			}
		}
		map.put("topicSetting", list);
    	String titleSetting = StringUtils.null2String(oq.getTitleSetting());
    	if(!"".equals(titleSetting)){
    		Map<String, Object> mapSetting = new HashMap<String, Object>();
    		mapSetting = JsonUtils.readValue(titleSetting);
    		map.put("titleSetting", mapSetting);
    	}else{
    		map.put("titleSetting", titleSetting);
    	}
    	map.put("entity", oq);
    	map.put("topicAnswerNum", num);
		return OperationResult.buildSuccessResult(map);
	}
	
	/**
     * 查询问卷题目
     * @return
     */
	@RequestMapping(value = "/getQuesByUserName")
    @ResponseBody
    public OperationResult getQuesByUserName(HttpServletRequest request) {
		String quesitionnaireId = request.getParameter("quesitionnaireId");
		if(quesitionnaireId != null && !ValidateUtils.validateId(quesitionnaireId)){
    		throw new ValidationException("非法参数");
	    }
		String userId = request.getParameter("userId");
		if(userId != null && !ValidateUtils.validateId(userId)){
    		throw new ValidationException("非法参数");
	    }
		WebUser user = WebUtils.getCurrentUser();
		String corpId = WebUtils.getCurrentUser().getCorpId();
		List<QuestionnaireTopic> list = topicService.getTopicOPtionInfo(quesitionnaireId,userId,user.getJwtToken(),true);
		Map<String, Object> map = new HashMap<>();
		QusetionnaireAnswerStatus qusetionnaireAnswerStatus =
				anStatusService.findAnswerStatus(userId,quesitionnaireId);
		if(qusetionnaireAnswerStatus != null){
			map.put("anStatus",qusetionnaireAnswerStatus.getStatus());
		}
		//Lambda表达式 查询所有分页页数
		List<String> pageList = list.stream().map((topic)->{
			if(StringUtils.equals(topic.getTopicType(),"paging")){
				return topic.getPage();
			}else{
				return null;
			}
		}).collect(Collectors.toList());
		if (CollectionUtils.isNotEmpty(list)) {
			int index = 0;
			for (int i = 0; i < list.size(); i++) {
				QuestionnaireTopic questionnaireTopic = list.get(i);
				String topicType = questionnaireTopic.getTopicType();
				if (!"paging".equals(topicType) && !"illustrate".equals(topicType)) {
					index++;
				}
				questionnaireTopic.setTopicNo(String.valueOf(index));
			}
		}
		map.put("topicSetting", list);
		if(CollectionUtils.isNotEmpty(pageList)){
			pageList.removeAll(Collections.singleton(null));
			if(pageList.size() == 0){
				map.put("page",0);
			}else{
				map.put("page",pageList.size());
			}
		}else{
			map.put("page",0);
		}
		String url ="";
		map.put("topicSetting", list);
		if(list != null && list.size() > 0) {
			for (QuestionnaireTopic questionnaireTopic : list) {
				if(questionnaireTopic.getList() != null && questionnaireTopic.getList().size() > 0) {
					for(int j=0;j<questionnaireTopic.getList().size();j++){
						QuestionnaireTopicOptions option = questionnaireTopic.getList().get(j);
						String jsonVal = option.getOptionSetting();
						QuestionnaireAnswer answer = option.getAnswer();
						if(jsonVal != null && !"".equals(jsonVal)&&!jsonVal.contains("option-option")) {
							JSONObject jsStr = JSONObject.parseObject(jsonVal);
							if( jsStr.getString("optionImg") != null && !"".equals(jsStr.getString("optionImg"))) {
								List<Map<String, String>> fileInfoList =attachmentUtilsService.getAttachmentByIds(jsStr.getString("optionImg"), corpId, user.getJwtToken());
								url = "/attachment/image?fid="+jsStr.getString("optionImg")+"&chksum="+fileInfoList.get(0).get("checksum");
								answer.setAttachment(url);
								option.setAnswer(answer);
							}
						}
					}
				}
			}
		}
    	Questionnaire oq = questionnaireService.findOne(quesitionnaireId);
    	String titleSetting = StringUtils.null2String(oq.getTitleSetting());
    	if(!"".equals(titleSetting)){
    		Map<String, Object> mapSetting = new HashMap<String, Object>();
    		mapSetting = JsonUtils.readValue(titleSetting);
    		map.put("titleSetting", mapSetting);
    	}else{
    		map.put("titleSetting", titleSetting);
    	}
    	map.put("entity", oq);
    	map.put("flexServerPath", GlobalConstant.getFlexServerPath(request));
		return OperationResult.buildSuccessResult(map);
	}
	
    /**
     * 问卷统计分析答卷列表
     * 
     * @param request
     * @return json
     */
    @RequestMapping(value = "/getPCAnswerDetail", method = RequestMethod.GET)
    @ResponseBody
    public Page<Map> getPCAnswerDetail(HttpServletRequest request) {
    	String quesitionnaireId = request.getParameter("quesitionnaireId");
    	if(quesitionnaireId != null && !ValidateUtils.validateId(quesitionnaireId)){
    		throw new ValidationException("非法参数");
	    }
    	Pageable pageable = PropertyFilter.buildPageableFromHttpRequest(request);
		List<PropertyFilter> propertyFilter = PropertyFilter.buildFiltersFromHttpRequest(QuestionnaireAnswer.class,request);
		String topicId = request.getParameter("topicId");
		if(topicId != null && !ValidateUtils.validateId(topicId)){
    		throw new ValidationException("非法参数");
	    }
		String topicType = request.getParameter("topicType");
		Page<Map> page = answerService.getPCAnswerDetail(pageable, propertyFilter, quesitionnaireId, topicType, topicId);
		List<Map> list = page.getContent();
		for(Map map : list) {
			if(map.get("userId")!=null&&StringUtils.isNotEmpty(topicId)) {
				if(topicType.equals(QuestionnaireTopic.TopicTypeEnum.FILLINBLANKS.getCode())) {
					List<Map> optionAnswerList = answerService.getOptionAndAnswer(map.get("userId").toString(),topicId);
					if(CollectionUtils.isNotEmpty(optionAnswerList)) {
						String answerText = "";
						float fraction = 0;
						for(Map map1 : optionAnswerList) {
							if(map1.get("answer")!=null&&!"".equals(map1.get("answer").toString())&&!"无".equals(map1.get("answer").toString())) {
								answerText += ValidateUtils.filter(map1.get("optionName").toString()+":"+map1.get("answer").toString())+"</br>";
							}else {
								answerText += map1.get("optionName").toString()+":"+"无"+"</br>";
							}
							fraction += (map1.get("fraction") != null ? Float.valueOf(StringUtils.null2String(map1.get("fraction"))) : 0);
						}
						map.put("answerText", answerText);
						map.put("fraction", fraction);
					}
				}else if(topicType.equals(QuestionnaireTopic.TopicTypeEnum.ANSWER.getCode()) || topicType.equals("shortAnswer")){
					List<Map> answerList = answerService.getOptionAndAnswer(map.get("userId").toString(),topicId);
					if(CollectionUtils.isNotEmpty(answerList)) {
						String answerText = "";
						float fraction = 0;
						for(Map map1 : answerList) {
							if(map1.get("answer")!=null&&!"".equals(map1.get("answer").toString())&&!"无".equals(map1.get("answer").toString())) {
								answerText += map1.get("answer").toString(); 
							}else {
								answerText += "无";
							}
							fraction += (map1.get("fraction") != null ? Float.valueOf(StringUtils.null2String(map1.get("fraction"))) : 0);
						}
						map.put("answerText", ValidateUtils.filter(answerText));
						map.put("fraction", "".equals(fraction) ? "0" : fraction);
					}
				}else if(topicType.equals(QuestionnaireTopic.TopicTypeEnum.FIELD.getCode())) {
					String userId = StringUtils.null2String(map.get("userId"));
					List<Map> fieldAnswerList = answerService.getOptionAndAnswer(userId,topicId);
					if(CollectionUtils.isNotEmpty(fieldAnswerList)) {
						String answerText = "";
						String attachmentId = "";
						String attachmentHtml = "";
						float fraction = 0;
						StringBuffer file = new StringBuffer();
						for(Map map1 : fieldAnswerList) {
							attachmentId = StringUtils.null2String(map1.get("answer")); 
							if (StringUtils.isNotBlank(attachmentId)) {
								answerText = attachmentUtilsService.getAttachmentInfo(attachmentId, TOKEN);
								 file.append("[").append(answerText).append("]");
							}
							fraction += (map1.get("fraction") != null ? Float.valueOf(StringUtils.null2String(map1.get("fraction"))) : 0);
						}
						if(file.toString()!=null&&!"".equals(file.toString())) {
							attachmentHtml = file.toString();
						}else {
							attachmentHtml = "无";
						}
						map.put("answerText", attachmentHtml);
						map.put("fraction", "".equals(fraction) ? "0" : fraction);
					}
				}
			}
		}
		return page;
    }
    
    /**
     * 主观题打分
     * @param request
     * @param id
     * @param fraction
     * @return
     */
	@RequestMapping(value = "/setFraction", method = RequestMethod.POST)
	@ResponseBody
	public OperationResult setFraction(HttpServletRequest request, @RequestParam("id") String id, @RequestParam("fraction") String fraction) {
		try {
			QuestionnaireAnswer qa = answerService.findOne(id);
			if(StringUtils.isNotEmpty(fraction)){
				qa.setFraction(Float.parseFloat(fraction));
			}
			answerService.save(qa);
			return OperationResult.buildSuccessResult();
		} catch (Exception e) {
			e.printStackTrace();
			return OperationResult.buildSuccessResult("打分失败");
		}
	}
	
	
	/**
	 * 是否能重新答题：如果是考试试卷且状态是已提交，如果考试设置，设置了重复答题和考试成绩，则重复答题设置和成绩条件都满足，如果设置了其中之一的条件，那么只满足其中之一即可。
	 * @param status
	 * @param ques
	 * @return
	 */
	public boolean canToAnswer(QusetionnaireAnswerStatus status,Questionnaire ques){
		if(("1".equals(status.getStatus())||"4".equals(status.getStatus())) && "questionnaireExam".equals(ques.getType())){
			if(("1".equals(ques.getNoLimit()) && (StringUtils.isNotBlank(ques.getPassScore())?status.getGrade()<Float.valueOf(ques.getPassScore()):true)) 
					||("0".equals(ques.getNoLimit()) && (StringUtils.isNotBlank(ques.getPassScore())?status.getGrade()<Float.valueOf(ques.getPassScore()):true) && status.getAnswerNum()<Integer.valueOf(ques.getAnswerNum()))
					||(!"1".equals(ques.getNoLimit()) && !"0".equals(ques.getNoLimit()) && (
							StringUtils.isNotBlank(ques.getPassScore())?status.getGrade()<Float.valueOf(ques.getPassScore()):false))){
				return  true;
			}
		}
		return  false;
	}
	
	/**
	 * 查询是否能再次答卷信息
	 * @param request
	 * @param quesId
	 * @return
	 */
	@RequestMapping(value = "/getCanAgainAnswerInfo", method = RequestMethod.GET)
	@ResponseBody
	public OperationResult getCanAgainAnswerInfo(HttpServletRequest request, @RequestParam("quesId") String quesId) {
		WebUser user=WebUtils.getCurrentUser();
		QusetionnaireAnswerStatus aStatus = anStatusService.findAnswerStatus(user.getUserId(),quesId);
		Questionnaire ques=questionnaireService.findOne(quesId);
		Map<String,Object> reData=new HashMap<>();
		reData.put("canAnswer", true);
		if(aStatus!=null && ques!=null) {
//			List<Map> reMapList=questionnaireService.findByListNativeQuery("select count(1) as count from oa_questionnaire_topic qt where  qt.questionnaire_id='"+quesId+"' and topic_type='field'", "");
//			if(reMapList!=null&&reMapList.size()>0) {
//				Map map=reMapList.get(0);
//				Integer count=Integer.valueOf(String.valueOf(map.get("count")));
//				if(count>0) {
//					
//				}
//			}
			reData.put("canAnswer", canToAnswer(aStatus,ques));
		}
		return OperationResult.buildSuccessResult("获取成功",reData);
	}
}